package itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import itheima.reggie.common.CustomException;
import itheima.reggie.common.R;
import itheima.reggie.dto.SetmealDishDto;
import itheima.reggie.dto.SetmealDto;
import itheima.reggie.entity.Category;
import itheima.reggie.entity.Setmeal;
import itheima.reggie.entity.SetmealDish;
import itheima.reggie.service.CategoryService;
import itheima.reggie.service.DishService;
import itheima.reggie.service.SetmealDishService;
import itheima.reggie.service.SetmealService;
import itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping
    public R<String> saveSetmeal(@RequestBody SetmealDto dto){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        setmealService.saveSetmealWithDish(dto);
        /*//清除redis中对应缓存
        redisTemplate.delete("setmeal_"+dto.getCategoryId()+"_1");*/
        return R.success("新增套餐成功！");
    }

    @GetMapping("/page")
    public R<Page<SetmealDto>> querySetmeal(int page,int pageSize,String name){
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> page2=new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Setmeal::getName,name);
        queryWrapper.orderByAsc(Setmeal::getStatus).orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo, queryWrapper);
        BeanUtils.copyProperties(pageInfo,page2,"records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> dtos = records.stream().map((item -> {
            SetmealDto dto = new SetmealDto();
            BeanUtils.copyProperties(item, dto);
            Category category = categoryService.getById(item.getCategoryId());
            dto.setCategoryName(category.getName());
            return dto;
        })).collect(Collectors.toList());
        page2.setRecords(dtos);
        return R.success(page2);
    }

    /**
     * 返回套餐信息
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public R<SetmealDto> querySetmealById(@PathVariable Long id){
        SetmealDto dishDto = setmealService.queryById(id);

        return R.success(dishDto);
    }
    @PutMapping
    public  R<String> editSetmeal(@RequestBody  SetmealDto dto){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        setmealService.editSetmeal(dto);
        redisTemplate.delete("setmeal_"+dto.getCategoryId()+"_1");
        return R.success("修改成功！");
    }
    /**
     * 批量启用与停用
     */
    @PostMapping("/status/{state}")
    public R<String> convertStatus(Long[] ids, @PathVariable Integer state) {
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        Setmeal setmeal;
        for (Long id:ids) {
            setmeal = setmealService.getById(id);
            setmeal.setStatus(state);
            setmealService.updateById(setmeal);
        }
        return R.success("1");
    }

    /**
     * 删除套餐
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> deleteSetmeal(@RequestParam List<Long> ids){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        try {
            setmealService.deleteSetmealWithDish(ids);
        }catch (CustomException e){
            return R.error(e.getMessage());
        }
        return R.success("套餐删除成功！");
    }
    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        List<Setmeal> list=null;
       /* //从redis中取数据
        String key="setmeal_"+setmeal.getCategoryId()+"_1";
         list= (List<Setmeal>)redisTemplate.opsForValue().get(key);
         if (list!=null){
             //如果取到直接返回
             return R.success(list);
         }*/
        //取不到查询数据库,保存到redis
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        list = setmealService.list(queryWrapper);
       /* //取不到查询数据库,保存到redis
        redisTemplate.opsForValue().set(key,list,60, TimeUnit.MINUTES);*/
        return R.success(list);
    }
    @GetMapping("/dish/{id}")
    @Cacheable(value = "setmealDishCache",key = "'setmeal_'+#id")
    public R<List<SetmealDishDto>> dish(@PathVariable Long id){
        List<SetmealDish> dishList=new ArrayList<>();
        LambdaQueryWrapper<SetmealDish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(wrapper);
        List<SetmealDishDto> collect = list.stream().map(item -> {
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            BeanUtils.copyProperties(item, setmealDishDto);
            setmealDishDto.setImage(dishService.getById(item.getDishId()).getImage());
            return setmealDishDto;
        }).collect(Collectors.toList());
        return R.success(collect);
    }
}
